namespace Legend
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// Provides the current time of the system, similar to DateTime.Now but
    /// can be modified through the SetCurrentProvider-method.
    /// </summary>
    public static class SystemTime
    {
        private static SystemTimeProvider currentProvider = () => DateTime.Now;

        /// <summary>
        /// Gets the current time of the system.
        /// </summary>
        public static DateTime Now
        {
            get
            {
                return SystemTime.currentProvider.Invoke();
            }
        }

        /// <summary>
        /// Sets the time provider to use.
        /// </summary>
        /// <param name="systemTimeProvider">The time provider to use.</param>
        /// <returns>An IDisposable instance that resets the previous provider when
        /// disposed.</returns>
        public static IDisposable SetCurrentProvider(SystemTimeProvider systemTimeProvider)
        {
            Require.ThatArgument(systemTimeProvider).Named("systemTimeProvider").IsNotNull();

            var resetter = new ProviderResetter() { PreviousProvider = SystemTime.currentProvider };
            SystemTime.currentProvider = systemTimeProvider;
            return resetter;
        }

        private class ProviderResetter
            : IDisposable
        {
            public SystemTimeProvider PreviousProvider;

            public void Dispose()
            {
                SystemTime.currentProvider = PreviousProvider;
            }
        }
    }
}

